﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using NAudio.Wave;

namespace AudioRecoder
{
    public partial class Form1 : Form
    {
        bool _recording = false;

        WaveIn _waveInStream = null;
        DirectSoundOut _dsound = null;

        public Form1()
        {
            InitializeComponent();

            // List wave in devices
            int waveInDevices = WaveIn.DeviceCount;
            for (int waveInDevice = 0 ; waveInDevice < waveInDevices ; ++waveInDevice)
            {
                WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
                lb_WaveInDevs.Items.Add(String.Format("Device {0}: {1}, {2} channels",
                    waveInDevice, deviceInfo.ProductName, deviceInfo.Channels));
            }

            // List wave out devices
            int waveOutDevices = WaveOut.DeviceCount;
            for (int waveOutDevice = 0; waveOutDevice < waveOutDevices; ++waveOutDevice)
            {
                WaveOutCapabilities deviceInfo = WaveOut.GetCapabilities(waveOutDevice);
                lb_WaveOutDevs.Items.Add(String.Format("Device {0}: {1}, {2} channels",
                    waveOutDevice, deviceInfo.ProductName, deviceInfo.Channels));
            }
        }

        public void StartRecord()
        {
            if (_waveInStream == null)
            {
                _waveInStream = new WaveIn();
                _waveInStream.DeviceNumber = 0;
                _waveInStream.DataAvailable += OnDataAvailable;
                _waveInStream.WaveFormat = new WaveFormat(8000, 1);
            }

            if (_dsound == null)
            {
                _dsound = new DirectSoundOut();
                WaveInProvider pvd = new WaveInProvider(_waveInStream);
                _dsound.Init(pvd);

            }

            _waveInStream.StartRecording();
            _dsound.Play();
            _recording = true;
        }

        public void StopRecord()
        {
            if (_waveInStream != null)
            {
                _waveInStream.StopRecording();
                _waveInStream = null;
            }

            if (_dsound != null)
            {
                _dsound.Stop();
                _dsound = null;
            }

            _recording = false;
        }

        private void OnDataAvailable(object sender, WaveInEventArgs e)
        {

        }

        private void OnRecord(object sender, EventArgs e)
        {
            if (_recording)
            {
                StopRecord();
                btn_Record.Text = "Start Recording";
            }
            else
            {
                StartRecord();
                btn_Record.Text = "Stop Recording";
            }
        }
    }
}
